package vip.meeet.thread.lock;

import java.util.concurrent.locks.LockSupport;

public class LockSupportPrinter {

    private int loopNum;
    static Thread a = null,b = null,c=null;

    public LockSupportPrinter(int loopNum) {
        this.loopNum = loopNum;
    }

    public void print(String message, Thread current, Thread next) {
        for (int i = 0; i < loopNum; i++) {
            //阻塞当前线程
            LockSupport.park(current);
            //线程被唤醒后打印
            System.out.print(message);
            //唤醒下一个线程
            LockSupport.unpark(next);
        }
    }

    public static void main(String[] args) {
        LockSupportPrinter lockSupportPrinter = new LockSupportPrinter(5);

        a = new Thread(() -> {
            lockSupportPrinter.print("a", a, b);
        });
        b = new Thread(() -> {
            lockSupportPrinter.print("b", b, c);
        });
        c = new Thread(() -> {
            lockSupportPrinter.print("c", c, a);
        });
        a.start();
        b.start();
        c.start();
        //主线程唤醒a，不需要等待a启动后就可以唤醒，因为提前唤醒，下一次LockSupport.park(a)将不被阻塞
        LockSupport.unpark(a);
    }
}
